#!/usr/bin/env python
#coding:utf-8

import sys
import time
import random
import logging
import comm.common_tools as commtools
import qianqian.qianqian_tools as qqtools


moon_ip = '192.168.217.14'
moon_port = '5999'
MOON_ADDR = (moon_ip, int(moon_port))


def makePushData(line):
	line = line[line.find('{')+1:-2]
	item = line.split('\t', 6)

	data = {'cmd_no'    : int(item[0]),			# cmd_no         uint64        指令序号
	        'cmd_type'  : int(item[1]),			# cmd_type       uint32        指令类型编号
	        'item_id'   : int(item[2]),			# item_id        uint64        Item的全局id
	        'item_type' : int(item[3]),			# item_type      uint32        Item的类型, 专辑、艺人、歌曲、演出
	        'op_type'   : int(item[4]),			# op_type        uint32        操作类型, INSERT, UPDATE, DELETE
	        'pub_status': int(item[5]),			# pub_status     uint32        发布状态，已发布，未发布
			'timestamp' : int(time.time()),		# timestamp      uint32        发包时间
	        'priority'  : 0,					# priority       uint32        指令的优先级，0为最低
	        'cmd_len'   : len(line),  			# cmd_len        uint32        指令正文内存的长度
	        'cmd_data'  : line,       			# cmd_data       char[]        指令正文，变长的字符串
	        }
	return data


def push_sink_data(file_path, sleep_ms):

	sleep_s = sleep_ms / 1000.0
	qq_obj = qqtools.NsheadTsheadMcpack()
	ns_head = qq_obj.get_ns_head()
	ns_head['provider'] = 'pushsys'

	stat = [0]*2
	with open(file_path, 'r') as f:
		for line in f:
			stat[0] += 1

			ns_head['log_id'] = random.randint(10000000, 99999999)
			data = makePushData(line)
#			logging.error(line)
			rts = qq_obj.send_nstsmc(MOON_ADDR, ns_head, None, data)

			if rts is False or 'mcpack' not in rts or rts['mcpack']['resp_code'] != 0:
				print stat[0], rts
				time.sleep(1)
			else:
				print stat[0], rts['mcpack']
				stat[1] += 1

			time.sleep(sleep_s)

	print '共 %d 条记录，发送成功 %d 条，失败 %d 条，成功率 %.2f%%\n' % (stat[0], stat[1], stat[0]-stat[1], 100*stat[1]/stat[0])
	return

def push_update_data(service_name, update_time):
	qq_obj = qqtools.NsheadTsheadMcpack()
	ns_head = qq_obj.get_ns_head()
	ns_head['provider'] = service_name
	ts_head = qq_obj.get_ts_head()
	ts_head['data_type'] = "updatetime"

	data = {'UpdateTime' : update_time}
	rts = qq_obj.send_nstsmc(MOON_ADDR, ns_head, ts_head, data)
	if rts is False or 'mcpack' not in rts or rts['mcpack']['resp_code'] != 0:
		print '发送成功后，moon会直接断开连接而不回复数据，所以这里无法判断调用是否正确', rts
	else:
		print 'ooooo', rts


#   logging.info('========STARTUP pid=[%d] cmd=%s ========' % (os.getpid(), sys.argv))
def main():
	commtools.init_log()
	argvlen = len(sys.argv)

	if sys.argv[1] == '-t' :
		item = sys.argv[2]
		time = sys.argv[3]
		print 'send time[%s] to svr[%s]' % (time, item)
		#push_update_data('psvr', '20190120:123456')
		push_update_data(item, time)
	elif sys.argv[1] == '-f' :
		filename = sys.argv[2]
		sleep_ms = sys.argv[3] if argvlen >=4 else '500'
		print 'send file[%s] to moon, with interval is %s ms' % (filename, sleep_ms)
		push_sink_data(filename, int(sleep_ms))


if __name__ == "__main__":
	argc = len(sys.argv)
	if 2 > argc or ('-v' == sys.argv[1] or '-h' == sys.argv[1]):
		print '\n'
		print '\t command line is like \'python %s -f/-t/-v/-h\'' % __file__
		print '\t             帮助信息：python %s -v/-h' % __file__
		print '\t             发送数据：python %s -f file_name [sleep_ms=500]' % __file__
		print '\t         发送重传时间：python %s -t svr_name 20190120:123456' % __file__
		print '\n'
	else:
		main()


'''
	LiangQuan, 2019/01/31,
	向moon发送数据的脚本；moon的地址和端口，暂时在py里硬编码
	发送的数据在文件中，以参数形式传递给脚本，文件格式为moon的original保存的数据
'''
